<?php
namespace app\common\model;

use think\model\concern\SoftDelete;

class Job extends Base
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    /**
     * 获取类别
     * @param int $total  业绩
     */
    public static function getCate($total = 0)
    {
        $list = JobCate::getList([], 0, 0, 0, '*', 'total DESC');

        $cateId = 0;
        foreach($list as $info){
            if($total >= $info['total']){
                $cateId = $info['id'];
                break;
            }
        }

        return $cateId;
    }

    /**
     * 查询职位列表
     * @param string|array $where  查询条件
     * @param int          $page  页数
     * @param int          $isAll  是否查询全部
     */
    public static function getJobList($where, $page = 1, $isAll = 0, $sort = 0)
    {
        if($sort == 2){
            $sorts = 'is_show DESC, total DESC, id DESC';
        }else if($sort == 3){
            $sorts = 'is_show DESC, need_num DESC, id DESC';
        }else{
            $sorts = 'is_show DESC, status, id DESC';
        }

        if($isAll == 0){
            $list = Job::getList($where, 1, $page, 20, '*', $sorts);
        }else{
            $list = Job::getList($where, 0, 0, 0, 'id, name');
        }

        if($list === false) return $list;

        $education   = [0 => '不限', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '大专', 5 => '本科', 6 => '硕士', 7 => '博士'];
        $recruitType = [0 => '不限', 1 => '校招', 2 => '社招'];

        if($isAll == 0){
            foreach($list as &$info){
                /** 参与人数 */
                $partakeNum = JobDistribution::alias('jd')
                    ->where(['jd.job_id' => $info['id']])
                    ->join('user u', 'jd.staff_id=u.id')
                    ->count();

                if($info['exp_low'] != 0 && $info['exp_high'] == 0){
                    $exp = $info['exp_low'] . '年以上';
                }else{
                    $exp = $info['exp_low'] . '-' . $info['exp_high'];
                }

                /** 未回答的问题数量 */
                $isAnswer = JobQa::getNum([['job_id', '=', $info['id']], ['answer_time', '=', 0]]);

                /** 服务费列表 */
                $totalList = JobTotal::getList(['job_id' => $info['id']]);
                
                $info['total']          = self::getTotal($info['id']);
                $info['reality_radio']  = $info['reality_radio'];
                $info['project_name']   = Project::getVal(['id' => $info['project_id']], 'name');
                $info['quality_name']   = JobQuality::getVal(['id' => $info['quality_id']], 'name');
                $info['user_name']      = User::getVal(['id' => $info['user_id']], 'name');
                $info['cate_name']      = JobCate::getVal(['id' => $info['cate_id']], 'name');
                $info['education_name'] = $education[$info['education']];
                $info['recruit_type']   = $recruitType[$info['recruit_type']];
                $info['salary']         = setSalary($info['salary_low']) . '-' . setSalary($info['salary_high']);
                $info['exp']            = $exp;
                $info['partake_num']    = $partakeNum;
                $info['invite_num']     = ResumeRound::getNum([['job_id', '=', $info['id']], ['status', '>=', 2]]);
                $info['pass_num']       = ResumeRound::getNum([['job_id', '=', $info['id']], ['status', 'in', [4, 5]]]);
                $info['recruit_num']    = ResumeRound::getNum([['job_id', '=', $info['id']], ['status', '=', 5]]);
                $info['total_num']      = self::setJobAchie($info['id']);
                $info['is_answer']      = $isAnswer;
                $info['total_list']     = $totalList ? $totalList : [];
    
                unset($info['user_id']);
            }
        }

        return $list;
    }

    /**
     * 获取项目名称
     * @param int $jobId  职位ID
     */
    public static function getPorjectName($jobId = 0)
    {
        $info = self::getFind(['id' => $jobId]);
        if(!$info) return '';

        $projectName = Project::getVal(['id' => $info['project_id']], 'name');
        if(empty($projectName)) return $info['name'];
        return $info['name'] . '（' . $projectName . '）';
    }

    /**
     * 计算某月的业绩
     * @param int $userId 员工ID
     * @param string $day 日期（年月）
     */
    public static function setAchie($userId = 0, $day = '')
    {
        $where = [];

        /** 总业绩 */
        $total = 0;

        if($userId != 0){
            if(is_array($userId)){
                $where[] = ['user_id', 'in', $userId];
            }else{
                $where[] = ['user_id', '=', $userId];
            }
        }

        /** 入职职位 */
        $model = ResumeRound::where($where)->where(['status' => 5]);

        if(!empty($day)){
            $list = $model->whereMonth('join_time', $day)->select();
        }else{
            $list = $model->select();
        }

        if($list->isEmpty()) return $total;

        foreach($list as $info){
            $total += self::getTotal($info['job_id']) * JobRadioRecord::getJobRadio($info['job_id'], $info['join_time']);
        }

        return $total;
    }

    /**
     * 计算某职位的业绩
     * @param int $jobId 职位ID
     * @param string $day 日期（年月）
     */
    public static function setJobAchie($jobId = 0)
    {
        /** 总业绩 */
        $total = 0;

        /** 入职职位 */
        $joinJobList = ResumeRound::where(['job_id' => $jobId, 'status' => 5])->select();
        if($joinJobList->isEmpty()) return $total;

        foreach($joinJobList as $info){
            $total += self::getTotal($info['job_id']) * JobRadioRecord::getJobRadio($info['job_id'], $info['invite_time']);
        }

        return $total;
    }

    /**
     * 获取职位服务费
     */
    public static function getTotal($jobId = 0)
    {
        if(!$jobId) return false;

        /** 入职人数 */
        $joinNum = ResumeRound::getNum([['job_id', '=', $jobId], ['status', '=', 5]]);

        $total = JobTotal::where([['job_id', '=', $jobId], ['join_num', '<=', $joinNum]])->max('total');

        if(!$total) return Job::getVal(['id' => $jobId], 'total');
        return $total;
    }
}